package utils;

import com.alibaba.fastjson.JSONObject;

import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * 经纬度转换工具类（在线版，基于高德地图API）
 * 功能：调用高德逆地理编码API，将经纬度转换为省份/城市
 * 文档：https://lbs.amap.com/api/webservice/guide/api/georegeo
 */
public class GeocodeUtil {
    // 高德地图开发者Key（需自行申请：https://lbs.amap.com/）
    private static final String AMAP_KEY = "116414d64c664dbaa4ce8b49bed74d04";
    // 逆地理编码API地址
    private static final String GEOCODE_URL = "https://restapi.amap.com/v3/geocode/regeo?location=%s,%s&key=%s";

    /**
     * 将经纬度转换为省份
     * @param longitude 经度（如116.404）
     * @param latitude 纬度（如39.915）
     * @return 省份名称（如"北京市"，失败返回"未知"）
     */
    public static String convertToProvince(Double longitude, Double latitude) {
        if (longitude == null || latitude == null) {
            return "未知";
        }

        // 1. 构建API请求URL
        String url = String.format(GEOCODE_URL, longitude, latitude, AMAP_KEY);

        // 2. 发送HTTP请求
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(url);
            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String result = EntityUtils.toString(entity);
                    return parseProvinceFromAmapResult(result);
                }
            }
        } catch (IOException | ParseException e) {
            e.printStackTrace(); // 实际生产环境建议使用日志框架
            return "未知";
        }

        return "未知";
    }

    /**
     * 解析高德API返回结果，提取省份
     */
    private static String parseProvinceFromAmapResult(String result) {
        JSONObject json = JSONObject.parseObject(result);
        String status = json.getString("status");
        if (!"1".equals(status)) {
            return "未知";
        }

        // 解析省份信息
        JSONObject regeocode = json.getJSONObject("regeocode");
        if (regeocode == null) {
            return "未知";
        }

        JSONObject addressComponent = regeocode.getJSONObject("addressComponent");
        if (addressComponent == null) {
            return "未知";
        }

        return addressComponent.getString("province");
    }

    // 测试方法
    public static void main(String[] args) {
        System.out.println(convertToProvince(117.7, 36.04));


        System.out.println(convertToProvince(115.12, 33.66));
    }
}
